package com.moyu.controller;

import com.moyu.pojo.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestOperations;

import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {


    @Autowired
    private  RestOperations restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/goods/{id}")
    public Goods findGoodsById(@PathVariable("id") int id){
        System.out.println("findGoodsById..."+id);



        //判断集合
        final List<ServiceInstance> instances = discoveryClient.getInstances("EUREKA-PROVIDER");
        if (instances==null||instances.size()==0){
            return  null;
        }

        final ServiceInstance serviceInstance = instances.get(0);
        final int hashCode = serviceInstance.hashCode();
        System.out.println("hashCode = " + hashCode);
        final int port = serviceInstance.getPort();
        System.out.println("port = " + port);

        String url = "http://"+hashCode+":"+port+"/goods/findOne/"+id;
        // 3. 调用方法


        Goods goods = restTemplate.getForObject(url, Goods.class);
        return goods;


        //远程调用Goods服务中的findOne接口

    }
}